<template>
  <span>
    <O2mTree
      :readonly="readonly"
      :records="value_display"
      :node="node"
      :parent-info="formInfo"
      @row-click="onRowClick"
      @row-new="onRowCreate"
    />

    <a-modal v-model:open="modalOpen" :title="node.string" width="600px">
      <O2mForm
        :readonly="readonly"
        :record="currentRow"
        :values="currentValues"
        :node="node"
        :parent-info="formInfo"
        @row-change="onRowChange"
      />

      <template #footer>
        <a-space v-if="readonly">
          <a-button size="small" @click="modalOpen = false"> 关闭 </a-button>
        </a-space>

        <a-space v-else>
          <a-button size="small" @click="onRowCommit"> 保存 </a-button>
          <a-button size="small" @click="onRowRollback"> 丢弃 </a-button>
          <a-button v-if="currentRow.id" size="small" @click="onRowRemove">
            移出
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </span>
</template>

<script setup>
import O2mTree from '@/odoojs-antdv/OSubView/O2mTree.vue'
import O2mForm from '@/odoojs-antdv/OSubView/O2mForm.vue'

import { useOne2many } from './wO2mApi.js'

import { ref } from 'vue'

const props = defineProps(['modelValue', 'node', 'formInfo'])
const emit = defineEmits(['update:modelValue', 'change'])

const useData = useOne2many(props, { emit })

const { readonly, value_display } = useData

const { currentRow, currentValues } = useData
const { rowNew, rowPick, rowChange, rowRemove, rowCommit } = useData

const modalOpen = ref(false)

async function onRowCreate() {
  // console.log('onRowCreate ')

  rowNew()
  modalOpen.value = true
}

function onRowClick(record) {
  // console.log(record)

  rowPick(record)
  modalOpen.value = true
}

function onRowRollback() {
  // console.log('onRowRollback ')
  modalOpen.value = false
}

async function onRowRemove() {
  // console.log('onRowRemove ')
  rowRemove()
  modalOpen.value = false
}

function onRowChange(fname, value) {
  rowChange(fname, value)
}

function onRowCommit() {
  // console.log('onRowCommit ')
  rowCommit()
  modalOpen.value = false
}
</script>

<style type="text/css"></style>
